Sentiment Analysis dari postingan Twitter

Aryanto

Abstract

Tujuan Modelling ini adalah memprediksi sentimen untuk postingan Twitter tertentu menggunakan Python. Analisis sentimen dapat memprediksi banyak emosi berbeda yang melekat pada teks, tetapi dalam laporan ini hanya 3 hal utama yang dipertimbangkan: positif, negatif, dan netral. Dataset pelatihan kecil (lebih dari 5900 contoh) dan data di dalamnya sangat miring, yang sangat berdampak pada kesulitan membangun pengklasifikasi yang baik. Setelah membuat banyak fitur kustom, memanfaatkan representasi bag-of-words dan word2vec serta menerapkan algoritme Extreme Gradient Boosting, akurasi klasifikasi pada level 58% tercapai.

Used Python Libraries

Data was pre-processed using pandas, gensim and numpy libraries and the learning/validating process was built with scikit-learn. Plots were created using plotly.

Notebook code convention

This report was first prepared as a classical Python project using object oriented programming with maintainability in mind. In order to show this project as a Jupyter Notebook, the classes had to be splitted into multiple code-cells. In order to do so, the classes are suffixed with _PurposeOfThisSnippet name and they inherit one from another. The final class will be then run and the results will be shown.

Data source

The input data consisted two CSV files: train.csv (5971 tweets) and test.csv (4000 tweets) - one for training and one for testing. Format of the data was the following (test data didn't contain Category column):

Id Category Tweet
635930169241374720 neutral IOS 9 App Transport Security. Mm need to check if my 3rd party network pod supports it

All tweets are in english, so it simplifies the processing and analysis.

Data preprocessing

Loading the data

The code snippet above is prepared, to load the data form the given file for further processing, or just read already preprocessed file from the cache. There's also a distinction between processing testing and training data. As the test.csv file was full of empty entries, they were removed. Additional class properties such as data_model, wordlist etc. will be used further.

Data distribution

First thing that can be done as soon as the data is loaded is to see the data distribution. The training set had the following distribution:

Preprocessing steps

The targed of the following preprocessing is to create a Bag-of-Words representation of the data. The steps will execute as follows:

  1. Cleansing
    1. Remove URLs
    2. Remove usernames (mentions)
    3. Remove tweets with *Not Available* text
    4. Remove special characters
    5. Remove numbers
  2. Text processing
    1. Tokenize
    2. Transform to lowercase
    3. Stem
  3. Build word list for Bag-of-Words

Cleansing

For the purpose of cleansing, the TwitterCleanup class was created. It consists methods allowing to execute all of the tasks show in the list above. Most of those is done using regular expressions. The class exposes it's interface through iterate() method - it yields every cleanup method in proper order.

The loaded tweets can be now cleaned.

Tokenization & stemming

For the text processing, nltk library is used. First, the tweets are tokenized using nlkt.word_tokenize and then, stemming is done using PorterStemmer as the tweets are 100% in english.

Building the wordlist

The wordlist (dictionary) is build by simple count of occurences of every unique word across all of the training dataset.

Before building the final wordlist for the model, let's take a look at the non-filtered version:

The most commont words (as expected) are the typical english stopwords. We will filter them out, however, as purpose of this analysis is to determine sentiment, words like "not" and "n't" can influence it greatly. Having this in mind, this word will be whitelisted.

Still, there are some words that seem too be occuring to many times, let's filter them. After some analysis, the lower bound was set to 3.

The wordlist is also saved to the csv file, so the same words can be used for the testing set.

Bag-of-words

The data is ready to transform it to bag-of-words representation.

Let's take a look at the data and see, which words are the most common for particular sentiments.

Some of the most common words show high distinction between classes like go and see and other are occuring in similiar amount for every class (plan, obama).

None of the most common words is unique to the negative class. At this point, it's clear that skewed data distribution will be a problem in distinguishing negative tweets from the others.

Classification

First of all, lets establish seed for random numbers generators.

The following utility function will train the classifier and show the F1, precision, recall and accuracy scores.

Experiment 1: BOW + Naive Bayes

It is nice to see what kind of results we might get from such simple model. The bag-of-words representation is binary, so Naive Bayes Classifier seems like a nice algorithm to start the experiments.

The experiment will be based on 7:3 train:test stratified split.

Result with accuracy at level of 58% seems to be quite nice result for such basic algorithm like Naive Bayes (having in mind that random classifier would yield result of around 33% accuracy). This performance may not hold for the final testing set. In order to see how the NaiveBayes performs in more general cases, 8-fold crossvalidation is used. The 8 fold is used, to optimize speed of testing on my 8-core machine.

This result no longer looks optimistic. For some of the splits, Naive Bayes classifier showed performance below the performance of random classifier.

Additional features

In order to not push any other aglorithm to the limit on the current data model, let's try to add some features that might help to classify tweets.

A common sense suggest that special characters like exclamation marks and the casing might be important in the task of determining the sentiment. The following features will be added to the data model:

Feature name Explanation
Number of uppercase people tend to express with either positive or negative emotions by using A LOT OF UPPERCASE WORDS
Number of ! exclamation marks are likely to increase the strength of opinion
Number of ? might distinguish neutral tweets - seeking for information
Number of positive emoticons positive emoji will most likely not occur in the negative tweets
Number of negative emoticons inverse to the one above
Number of ... commonly used in commenting something
Number of quotations same as above
Number of mentions sometimes people put a lot of mentions on positive tweets, to share something good
Number of hashtags just for the experiment
Number of urls similiar to the number of mentions

Extraction of those features must be done before any preprocessing happens.

For the purpose of emoticons, the EmoticonDetector class is created. The file emoticons.txt contains list of positive and negative emoticons, which are used.

Logic behind extra features

Let's see how (some) of the extra features separate the data set. Some of them, i.e number exclamation marks, number of pos/neg emoticons do this really well. Despite of the good separation, those features sometimes occur only on small subset of the training dataset.

Experiment 2: extended features + Random Forest

As a second attempt on the classification the Random Forest will be used.

The accuracy for the initial split was lower than the one for the Naive Bayes, but let's see what happens during crossvalidation:

It looks better, however it's still not much above accuracy of the random classifier and barely better than Naive Bayes classifier.

We can observe a low recall level of the RandomForest classifier for the negative class, which may be caused by the data skewness.

Summary

Experiment showed that prediction of text sentiment is a non-trivial task for machine learning. A lot of preprocessing is required just to be able to run any algorithm and see - usually not great - results. Main problem for sentiment analysis is to craft the machine representation of the text. Simple bag-of-words was definitely not enough to obtain satisfying results, thus a lot of additional features were created basing on common sense (number of emoticons, exclamation marks etc.). Word2vec representation significantly raised the predictions quality. I think that a slight improvement in classification accuracy for the given training dataset could be developed, but since it contained highly skewed data (small number of negative cases), the difference will be probably in the order of a few percent. The thing that could possibly improve classification results will be to add a lot of additional examples (increase training dataset), because given 5971 examples obviously do not contain every combination of words usage, moreover - a lot of emotion-expressing words surely are missing.